class ImageConverter {
    constructor() {
        this.files = [];
        this.convertedImages = [];
        this.supportedFormats = ['png', 'jpeg', 'webp', 'bmp', 'gif'];
        this.maxFileSize = 50 * 1024 * 1024; // 50MB
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.updateQualityDisplay();
        this.checkBrowserEnvironment();
        this.initThemeSwitcher();
    }

    // 初始化主题切换器
    initThemeSwitcher() {
        const themeToggle = document.getElementById('themeToggle');
        const themeMenu = document.getElementById('themeMenu');
        const themeOptions = document.querySelectorAll('.theme-option');
        
        // 从本地存储加载主题
        const savedTheme = localStorage.getItem('imageConverter-theme') || 'dark';
        this.setTheme(savedTheme);
        
        // 更新活动状态
        themeOptions.forEach(option => {
            option.classList.remove('active');
            if (option.dataset.theme === savedTheme) {
                option.classList.add('active');
            }
        });
        
        // 切换主题菜单显示
        themeToggle.addEventListener('click', (e) => {
            e.stopPropagation();
            themeMenu.classList.toggle('show');
        });
        
        // 点击外部关闭菜单
        document.addEventListener('click', (e) => {
            if (!e.target.closest('.theme-switcher')) {
                themeMenu.classList.remove('show');
            }
        });
        
        // 主题选择
        themeOptions.forEach(option => {
            option.addEventListener('click', () => {
                const theme = option.dataset.theme;
                this.setTheme(theme);
                
                // 更新活动状态
                themeOptions.forEach(opt => opt.classList.remove('active'));
                option.classList.add('active');
                
                // 保存到本地存储
                localStorage.setItem('imageConverter-theme', theme);
                
                // 关闭菜单
                themeMenu.classList.remove('show');
                
                // 显示切换提示
                this.showNotification(`已切换到${option.querySelector('span').textContent}`, 'success', 2000);
            });
        });
    }
    
    // 设置主题
    setTheme(theme) {
        // 移除所有主题类
        document.body.classList.remove('theme-light', 'theme-dark', 'theme-green', 'theme-blue', 'theme-purple');
        
        // 添加新主题类
        if (theme !== 'default') {
            document.body.classList.add(`theme-${theme}`);
        }
    }
    
    // 检查浏览器环境并给出提示
    checkBrowserEnvironment() {
        if (this.isInAppBrowser() && this.isMobileDevice()) {
            let browserName = '内置浏览器';
            let suggestion = '';
            
            if (this.isWeChatBrowser()) {
                browserName = '微信';
                // 检测是否为手机微信
                const isMobileWeChat = /Mobile/i.test(navigator.userAgent);
                if (isMobileWeChat) {
                    suggestion = '已为手机微信优化保存体验，转换后可直接长按图片保存';
                } else {
                    suggestion = '建议点击右上角菜单选择"在浏览器中打开"以获得更好的下载体验';
                }
            } else if (this.isQQBrowser()) {
                browserName = 'QQ';
                suggestion = '建议在外部浏览器中打开以获得更好的下载体验';
            } else {
                suggestion = '建议在外部浏览器中打开以获得更好的下载体验';
            }
            
            // 延迟显示提示，避免干扰页面加载
            setTimeout(() => {
                this.showNotification(`检测到${browserName}环境，${suggestion}`, 'info', 8000);
            }, 2000);
        }
    }
    
    // 检测是否为手机微信
    isMobileWeChat() {
        return this.isWeChatBrowser() && /Mobile/i.test(navigator.userAgent) && this.isMobileDevice();
    }

    setupEventListeners() {
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const convertBtn = document.getElementById('convertBtn');
        const downloadAllBtn = document.getElementById('downloadAllBtn');
        const qualitySlider = document.getElementById('qualitySlider');
        const namingRadios = document.querySelectorAll('input[name="naming"]');

        // 检测移动设备
        const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

        // 文件上传事件
        uploadArea.addEventListener('click', () => fileInput.click());
        fileInput.addEventListener('change', (e) => this.handleFiles(e.target.files));

        // 移动端触摸事件
        if (isMobile) {
            uploadArea.addEventListener('touchstart', (e) => {
                uploadArea.classList.add('dragover');
            });
            
            uploadArea.addEventListener('touchend', (e) => {
                uploadArea.classList.remove('dragover');
                // 延迟触发点击，避免双重触发
                setTimeout(() => fileInput.click(), 100);
            });
        }

        // 拖拽上传（桌面端）
        if (!isMobile) {
            uploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadArea.classList.add('dragover');
            });

            uploadArea.addEventListener('dragleave', () => {
                uploadArea.classList.remove('dragover');
            });

            uploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadArea.classList.remove('dragover');
                this.handleFiles(e.dataTransfer.files);
            });
        }

        // 转换按钮
        convertBtn.addEventListener('click', () => this.convertImages());

        // 下载全部按钮
        downloadAllBtn.addEventListener('click', () => this.downloadAll());

        // 质量滑块
        qualitySlider.addEventListener('input', () => this.updateQualityDisplay());

        // 命名方式切换
        namingRadios.forEach(radio => {
            radio.addEventListener('change', () => this.toggleCustomNaming());
        });
        
        // 移动端优化：防止页面缩放
        if (isMobile) {
            document.addEventListener('touchstart', (e) => {
                if (e.touches.length > 1) {
                    e.preventDefault();
                }
            }, { passive: false });
            
            let lastTouchEnd = 0;
            document.addEventListener('touchend', (e) => {
                const now = (new Date()).getTime();
                if (now - lastTouchEnd <= 300) {
                    e.preventDefault();
                }
                lastTouchEnd = now;
            }, false);
        }
    }

    handleFiles(files) {
        const validFiles = [];
        const errors = [];
        
        Array.from(files).forEach(file => {
            if (!file.type.startsWith('image/')) {
                errors.push(`${file.name}: 不是有效的图片文件`);
                return;
            }
            
            if (file.size > this.maxFileSize) {
                errors.push(`${file.name}: 文件大小超过50MB限制`);
                return;
            }
            
            validFiles.push(file);
        });
        
        if (errors.length > 0) {
            this.showNotification('部分文件无法处理：\n' + errors.join('\n'), 'warning');
        }
        
        if (validFiles.length === 0) {
            this.showNotification('请选择有效的图片文件！', 'error');
            return;
        }
        
        this.files = validFiles;
        this.showPreview();
        document.getElementById('settingsSection').style.display = 'block';
        this.animateSection('settingsSection');
    }

    showPreview() {
        const previewSection = document.getElementById('previewSection');
        const previewGrid = document.getElementById('previewGrid');
        
        previewGrid.innerHTML = '';
        
        this.files.forEach((file, index) => {
            const reader = new FileReader();
            reader.onload = (e) => {
                const previewItem = document.createElement('div');
                previewItem.className = 'preview-item';
                previewItem.innerHTML = `
                    <img src="${e.target.result}" alt="预览图片">
                    <div class="preview-info">
                        <h4>${file.name}</h4>
                        <p>大小: ${this.formatFileSize(file.size)}</p>
                        <p>类型: ${file.type}</p>
                    </div>
                `;
                previewGrid.appendChild(previewItem);
            };
            reader.readAsDataURL(file);
        });
        
        previewSection.style.display = 'block';
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    updateQualityDisplay() {
        const qualitySlider = document.getElementById('qualitySlider');
        const qualityValue = document.getElementById('qualityValue');
        qualityValue.textContent = Math.round(qualitySlider.value * 100) + '%';
    }

    toggleCustomNaming() {
        const customNaming = document.getElementById('customNaming');
        const namingValue = document.querySelector('input[name="naming"]:checked').value;
        customNaming.style.display = namingValue === 'custom' ? 'block' : 'none';
    }

    generateFileName(originalName, index, format) {
        const namingType = document.querySelector('input[name="naming"]:checked').value;
        const extension = format === 'jpeg' ? 'jpg' : format;
        
        switch (namingType) {
            case 'direct':
                // 保持原文件名，只改变扩展名
                const nameWithoutExt = originalName.replace(/\.[^/.]+$/, '');
                return `${nameWithoutExt}.${extension}`;
            case 'random':
                return `img_${this.generateRandomString(8)}.${extension}`;
            case 'numbered':
                return `image_${index + 1}.${extension}`;
            case 'custom':
                const customPrefix = document.getElementById('customNameInput').value.trim() || 'converted';
                return this.files.length > 1 ? `${customPrefix}_${index + 1}.${extension}` : `${customPrefix}.${extension}`;
            default:
                return `converted_${index + 1}.${extension}`;
        }
    }

    generateRandomString(length) {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let result = '';
        for (let i = 0; i < length; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return result;
    }

    async convertImages() {
        const format = document.querySelector('input[name="format"]:checked').value;
        const quality = parseFloat(document.getElementById('qualitySlider').value);
        const convertBtn = document.getElementById('convertBtn');
        
        convertBtn.disabled = true;
        convertBtn.innerHTML = '<span>转换中...</span>';
        
        // 创建进度条
        this.createProgressBar();
        
        this.convertedImages = [];
        
        try {
            for (let i = 0; i < this.files.length; i++) {
                const file = this.files[i];
                
                // 更新进度
                this.updateProgress((i / this.files.length) * 100, `正在转换: ${file.name}`);
                
                const convertedBlob = await this.convertImage(file, format, quality);
                const fileName = this.generateFileName(file.name, i, format);
                
                this.convertedImages.push({
                    blob: convertedBlob,
                    fileName: fileName,
                    originalFile: file,
                    compressionRatio: ((file.size - convertedBlob.size) / file.size * 100).toFixed(1)
                });
            }
            
            this.updateProgress(100, '转换完成！');
            setTimeout(() => {
                this.removeProgressBar();
                this.showDownloadSection();
                this.showNotification(`成功转换 ${this.files.length} 个文件！`, 'success');
            }, 500);
            
        } catch (error) {
            console.error('转换失败:', error);
            this.removeProgressBar();
            this.showNotification('图片转换失败，请重试！', 'error');
        } finally {
            convertBtn.disabled = false;
            convertBtn.innerHTML = '开始转换';
        }
    }

    convertImage(file, format, quality) {
        return new Promise((resolve, reject) => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            const img = new Image();
            
            img.onload = () => {
                canvas.width = img.width;
                canvas.height = img.height;
                
                // 如果转换为JPG，先填充白色背景
                if (format === 'jpeg') {
                    ctx.fillStyle = '#FFFFFF';
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                }
                
                ctx.drawImage(img, 0, 0);
                
                canvas.toBlob((blob) => {
                    if (blob) {
                        resolve(blob);
                    } else {
                        reject(new Error('转换失败'));
                    }
                }, `image/${format}`, quality);
            };
            
            img.onerror = () => reject(new Error('图片加载失败'));
            img.src = URL.createObjectURL(file);
        });
    }

    showDownloadSection() {
        const downloadSection = document.getElementById('downloadSection');
        const downloadGrid = document.getElementById('downloadGrid');
        
        downloadGrid.innerHTML = '';
        
        this.convertedImages.forEach((item, index) => {
            const downloadItem = document.createElement('div');
            downloadItem.className = 'download-item';
            
            const url = URL.createObjectURL(item.blob);
            const compressionText = item.compressionRatio > 0 ? 
                `压缩了 ${item.compressionRatio}%` : 
                `增大了 ${Math.abs(item.compressionRatio)}%`;
            
            downloadItem.innerHTML = `
                <div class="download-preview">
                    <img src="${url}" alt="转换后预览" style="width: 100%; height: 120px; object-fit: cover; border-radius: 8px; margin-bottom: 10px;">
                </div>
                <h4>${item.fileName}</h4>
                <div class="file-info">
                    <p><strong>原文件:</strong> ${item.originalFile.name}</p>
                    <p><strong>原大小:</strong> ${this.formatFileSize(item.originalFile.size)}</p>
                    <p><strong>新大小:</strong> ${this.formatFileSize(item.blob.size)}</p>
                    <p class="compression-info"><strong>变化:</strong> ${compressionText}</p>
                </div>
                <button class="download-btn" onclick="imageConverter.downloadSingle(${index})">
                    <span>📥</span> 下载
                </button>
            `;
            
            downloadGrid.appendChild(downloadItem);
        });
        
        downloadSection.style.display = 'block';
        this.animateSection('downloadSection');
    }

    downloadSingle(index) {
        const item = this.convertedImages[index];
        const url = URL.createObjectURL(item.blob);
        
        // 检测是否为移动设备
        const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        
        if (isMobile) {
            // 移动端处理：尝试多种下载方式
            this.mobileDownload(item.blob, item.fileName, url);
        } else {
            // 桌面端处理
            const a = document.createElement('a');
            a.href = url;
            a.download = item.fileName;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
        
        // 延迟释放URL，确保下载完成
        setTimeout(() => {
            URL.revokeObjectURL(url);
        }, 1000);
    }
    
    async mobileDownload(blob, fileName, url) {
        try {
            // 检测是否在内置浏览器中（微信、QQ等）
            if (this.isInAppBrowser()) {
                this.handleInAppBrowserDownload(blob, fileName, url);
                return;
            }
            
            // 首先尝试 Web Share API（如果支持）
            if (navigator.share && navigator.canShare) {
                const file = new File([blob], fileName, { type: blob.type });
                if (navigator.canShare({ files: [file] })) {
                    await navigator.share({
                        files: [file],
                        title: '保存转换后的图片',
                        text: `转换后的图片: ${fileName}`
                    });
                    this.showNotification('图片分享成功！请选择保存到相册', 'success');
                    return;
                }
            }
            
            // 方法1：强制下载（适用于大部分移动浏览器）
            const a = document.createElement('a');
            a.href = url;
            a.download = fileName;
            a.style.display = 'none';
            a.target = '_blank';
            
            // 添加到DOM并触发点击
            document.body.appendChild(a);
            
            // 使用多种方式触发下载
            a.click();
            
            // 延迟触发（某些浏览器需要）
            setTimeout(() => {
                a.click();
            }, 100);
            
            // 清理
            setTimeout(() => {
                document.body.removeChild(a);
            }, 1000);
            
            this.showNotification('正在尝试下载到手机...', 'info');
            
            // 如果3秒后还没成功，显示备用方案
            setTimeout(() => {
                this.fallbackMobileDownload(blob, fileName, url);
            }, 3000);
            
        } catch (error) {
            console.log('下载失败，使用备用方案:', error);
            this.fallbackMobileDownload(blob, fileName, url);
        }
    }
    
    // 处理内置浏览器（微信、QQ等）的下载
    handleInAppBrowserDownload(blob, fileName, url) {
        // 直接显示专门的内置浏览器保存界面
        this.createInAppBrowserSaveModal(blob, fileName, url);
    }
    
    // 尝试微信直接保存
    tryWeChatDirectSave(blob, fileName, url) {
        // 创建专门的微信保存界面
        const modal = document.createElement('div');
        modal.className = 'mobile-download-modal wechat-save';
        
        // 转换为base64以便微信处理
        const reader = new FileReader();
        reader.onload = (e) => {
            const base64Data = e.target.result;
            
            modal.innerHTML = `
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>📱 微信中保存图片</h3>
                        <button class="modal-close" onclick="this.parentElement.parentElement.parentElement.remove()">&times;</button>
                    </div>
                    <div class="modal-body">
                        <div class="wechat-notice">
                            <p class="notice-text">🔔 检测到手机微信环境，为您提供最佳保存方案</p>
                        </div>
                        
                        <div class="image-container" style="position: relative;">
                            <img id="wechatSaveImage" src="${base64Data}" alt="${fileName}" 
                                 style="max-width: 100%; height: auto; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); cursor: pointer;"
                                 onclick="this.requestFullscreen && this.requestFullscreen()">
                            <div class="image-overlay" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); 
                                 background: rgba(0,0,0,0.7); color: white; padding: 8px 16px; border-radius: 20px; 
                                 font-size: 14px; pointer-events: none; opacity: 0; transition: opacity 0.3s;">
                                长按保存
                            </div>
                        </div>
                        
                        <div class="wechat-instructions">
                            <p class="instruction-title">💡 <strong>推荐保存方法（按顺序尝试）：</strong></p>
                            <div class="instruction-step">
                                <span class="step-number">1</span>
                                <span class="step-text">直接长按上方图片，选择"保存到相册"</span>
                            </div>
                            <div class="instruction-step">
                                <span class="step-number">2</span>
                                <span class="step-text">点击图片进入全屏，再长按保存</span>
                            </div>
                            <div class="instruction-step">
                                <span class="step-number">3</span>
                                <span class="step-text">使用下方按钮在浏览器中打开</span>
                            </div>
                        </div>
                        
                        <p class="file-name">📄 文件名: ${fileName}</p>
                        
                        <div class="modal-actions">
                             <button class="action-btn primary" onclick="window.open('${url}', '_blank'); this.textContent='已打开浏览器';">🌐 在浏览器中打开</button>
                             <button class="action-btn secondary" onclick="document.getElementById('wechatSaveImage').click()">🖼️ 点击图片</button>
                             <button class="action-btn tertiary" id="wechatShareBtn">📤 尝试分享保存</button>
                             <button class="action-btn tertiary" onclick="this.parentElement.parentElement.parentElement.querySelector('.image-overlay').style.opacity='1'; setTimeout(() => this.parentElement.parentElement.parentElement.querySelector('.image-overlay').style.opacity='0', 2000)">💡 显示提示</button>
                         </div>
                        
                        <div class="wechat-tips">
                            <p class="tip-title">🔧 如果以上方法都不行：</p>
                            <p class="tip-item">• 尝试截屏保存（最后选择）</p>
                            <p class="tip-item">• 分享给自己或文件传输助手</p>
                            <p class="tip-item">• 复制链接到浏览器打开</p>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            
            // 添加图片长按事件监听
            const img = modal.querySelector('#wechatSaveImage');
            let pressTimer;
            
            img.addEventListener('touchstart', (e) => {
                pressTimer = setTimeout(() => {
                    // 显示长按提示
                    const overlay = modal.querySelector('.image-overlay');
                    overlay.style.opacity = '1';
                    overlay.textContent = '继续长按保存';
                    
                    // 尝试触发保存（某些情况下有效）
                    if (navigator.vibrate) {
                        navigator.vibrate(50);
                    }
                }, 500);
            });
            
            img.addEventListener('touchend', () => {
                clearTimeout(pressTimer);
                setTimeout(() => {
                    const overlay = modal.querySelector('.image-overlay');
                    overlay.style.opacity = '0';
                    overlay.textContent = '长按保存';
                }, 1000);
            });
            
            // 添加微信分享按钮事件
             const shareBtn = modal.querySelector('#wechatShareBtn');
             shareBtn.addEventListener('click', async () => {
                 try {
                     // 尝试使用Web Share API
                     if (navigator.share && navigator.canShare) {
                         const file = new File([blob], fileName, { type: blob.type });
                         if (navigator.canShare({ files: [file] })) {
                             await navigator.share({
                                 files: [file],
                                 title: '保存转换后的图片',
                                 text: `转换后的图片: ${fileName}`
                             });
                             shareBtn.textContent = '✅ 分享成功';
                             shareBtn.style.background = 'linear-gradient(45deg, #27ae60, #2ecc71)';
                             this.showNotification('请在分享选项中选择保存到相册 📱', 'success');
                             return;
                         }
                     }
                     
                     // 备用方案：复制图片数据到剪贴板
                     if (navigator.clipboard && navigator.clipboard.write) {
                         const clipboardItem = new ClipboardItem({
                             [blob.type]: blob
                         });
                         await navigator.clipboard.write([clipboardItem]);
                         shareBtn.textContent = '📋 已复制';
                         shareBtn.style.background = 'linear-gradient(45deg, #3498db, #2980b9)';
                         this.showNotification('图片已复制到剪贴板，可以粘贴保存 📋', 'success');
                     } else {
                         throw new Error('不支持分享功能');
                     }
                 } catch (error) {
                     console.log('分享失败:', error);
                     shareBtn.textContent = '❌ 分享失败';
                     shareBtn.style.background = 'linear-gradient(45deg, #e74c3c, #c0392b)';
                     this.showNotification('分享功能不可用，请尝试长按图片保存 📱', 'warning');
                 }
             });
             
             // 点击背景关闭模态框
             modal.addEventListener('click', (e) => {
                 if (e.target === modal) {
                     modal.remove();
                 }
             });
             
             this.showNotification('已为微信优化保存体验，请尝试长按图片 📱', 'success', 6000);
        };
        
        reader.readAsDataURL(blob);
    }
    
    // 创建内置浏览器专用的保存模态框
    createInAppBrowserSaveModal(blob, fileName, url) {
        // 先尝试微信特有的保存方式
        if (this.isMobileWeChat()) {
            this.tryWeChatDirectSave(blob, fileName, url);
            return;
        }
        
        const modal = document.createElement('div');
        modal.className = 'mobile-download-modal in-app-browser';
        
        let browserName = '内置浏览器';
        let specificInstructions = [];
        
        if (this.isWeChatBrowser()) {
            browserName = '微信';
            specificInstructions = [
                '点击右上角的 "···" 菜单',
                '选择 "在浏览器中打开"',
                '然后长按图片保存到相册'
            ];
        } else if (this.isQQBrowser()) {
            browserName = 'QQ';
            specificInstructions = [
                '点击右上角的菜单按钮',
                '选择 "在浏览器中打开"',
                '然后长按图片保存'
            ];
        } else {
            specificInstructions = [
                '尝试在外部浏览器中打开',
                '或长按图片选择保存选项'
            ];
        }
        
        const instructionsHtml = specificInstructions.map((instruction, index) => 
            `<p class="save-instruction">${index + 1}. ${instruction}</p>`
        ).join('');
        
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3>在${browserName}中保存图片</h3>
                    <button class="modal-close" onclick="this.parentElement.parentElement.parentElement.remove()">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="browser-notice">
                        <p class="notice-text">⚠️ 检测到您在${browserName}中打开，建议使用以下方式保存：</p>
                    </div>
                    <img src="${url}" alt="${fileName}" style="max-width: 100%; height: auto; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15);">
                    <div class="save-instructions">
                        <p class="save-instruction primary">📱 <strong>推荐保存方法：</strong></p>
                        ${instructionsHtml}
                    </div>
                    <p class="file-name">📄 文件名: ${fileName}</p>
                    <div class="modal-actions">
                         <button class="action-btn primary" onclick="window.open('${url}', '_blank')">🌐 在浏览器中打开</button>
                         <button class="action-btn secondary" onclick="this.parentElement.parentElement.parentElement.querySelector('img').click()">👆 点击图片</button>
                         <button class="action-btn tertiary" onclick="navigator.clipboard && navigator.clipboard.writeText('${url}').then(() => alert('图片链接已复制！'))">📋 复制链接</button>
                     </div>
                     <div class="download-tips">
                         <p class="tip-title">💡 其他保存方式：</p>
                         <p class="tip-item">• 长按图片 → 保存到相册</p>
                         <p class="tip-item">• 截屏保存（最后选择）</p>
                         <p class="tip-item">• 分享到其他应用保存</p>
                     </div>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
        
        // 点击背景关闭模态框
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.remove();
            }
        });
        
        this.showNotification(`已为${browserName}优化保存方式 🔧`, 'info');
    }
    
    fallbackMobileDownload(blob, fileName, url) {
        try {
            // 方法1：尝试使用 Data URL 下载
            const reader = new FileReader();
            reader.onload = (e) => {
                const dataUrl = e.target.result;
                
                // 创建下载链接
                const a = document.createElement('a');
                a.href = dataUrl;
                a.download = fileName;
                a.style.display = 'none';
                document.body.appendChild(a);
                
                // 尝试触发下载
                try {
                    a.click();
                    this.showNotification('正在使用备用方式下载...', 'info');
                } catch (clickError) {
                    // 如果点击失败，使用iframe方法
                    this.iframeDownload(dataUrl, fileName);
                }
                
                setTimeout(() => {
                    document.body.removeChild(a);
                }, 1000);
            };
            
            reader.onerror = () => {
                // 如果 FileReader 失败，显示保存模态框
                this.createSaveableImage(blob, fileName, url);
            };
            
            reader.readAsDataURL(blob);
            
        } catch (error) {
            console.log('备用下载方案失败:', error);
            // 最终方案：显示保存模态框
            this.createSaveableImage(blob, fileName, url);
        }
    }
    
    // iframe 下载方法
    iframeDownload(dataUrl, fileName) {
        try {
            const iframe = document.createElement('iframe');
            iframe.style.display = 'none';
            iframe.src = dataUrl;
            document.body.appendChild(iframe);
            
            setTimeout(() => {
                document.body.removeChild(iframe);
            }, 2000);
            
            this.showNotification('正在尝试iframe下载方式...', 'info');
            
            // 如果iframe方法也失败，显示保存模态框
            setTimeout(() => {
                const blob = this.dataURLtoBlob(dataUrl);
                const url = URL.createObjectURL(blob);
                this.createSaveableImage(blob, fileName, url);
            }, 2000);
            
        } catch (error) {
            console.log('iframe下载失败:', error);
            const blob = this.dataURLtoBlob(dataUrl);
            const url = URL.createObjectURL(blob);
            this.createSaveableImage(blob, fileName, url);
        }
    }
    
    // 将 Data URL 转换为 Blob
    dataURLtoBlob(dataURL) {
        const arr = dataURL.split(',');
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
    }
    
    // 检测是否为移动设备
    isMobileDevice() {
        return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }

    // 检测是否在微信内置浏览器中
    isWeChatBrowser() {
        return /MicroMessenger/i.test(navigator.userAgent);
    }

    // 检测是否在QQ内置浏览器中
    isQQBrowser() {
        return /QQ/i.test(navigator.userAgent) && !/MQQBrowser/i.test(navigator.userAgent);
    }

    // 检测是否在其他内置浏览器中
    isInAppBrowser() {
        return this.isWeChatBrowser() || this.isQQBrowser() || /FBAN|FBAV|Line|Weibo|MicroMessenger/i.test(navigator.userAgent);
    }

    // 获取设备类型和保存提示
    getDeviceInfo() {
        const userAgent = navigator.userAgent;
        let deviceType = 'unknown';
        let saveInstructions = [];
        
        if (/iPhone|iPad|iPod/i.test(userAgent)) {
            deviceType = 'ios';
            saveInstructions = [
                '长按图片',
                '选择"存储到相册"',
                '图片将保存到相册中'
            ];
        } else if (/Android/i.test(userAgent)) {
            deviceType = 'android';
            saveInstructions = [
                '长按图片',
                '选择"保存图片"或"下载图片"',
                '图片将保存到下载文件夹或相册'
            ];
        } else if (/webOS/i.test(userAgent)) {
            deviceType = 'webos';
            saveInstructions = [
                '长按图片',
                '选择保存选项',
                '图片将保存到设备中'
            ];
        } else {
            deviceType = 'mobile';
            saveInstructions = [
                '长按图片',
                '选择"保存图片"选项',
                '图片将保存到设备中'
            ];
        }
        
        return { deviceType, saveInstructions };
    }

    createSaveableImage(blob, fileName, url) {
        // 获取设备特定的保存说明
        const { deviceType, saveInstructions } = this.getDeviceInfo();
        
        // 创建一个模态框显示图片，用户可以长按保存
        const modal = document.createElement('div');
        modal.className = 'mobile-download-modal';
        
        const instructionsHtml = saveInstructions.map((instruction, index) => 
            `<p class="save-instruction">${index + 1}. ${instruction}</p>`
        ).join('');
        
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3>保存图片到手机</h3>
                    <button class="modal-close" onclick="this.parentElement.parentElement.parentElement.remove()">&times;</button>
                </div>
                <div class="modal-body">
                    <img src="${url}" alt="${fileName}" style="max-width: 100%; height: auto; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15);">
                    <div class="save-instructions">
                        <p class="save-instruction primary">📱 <strong>保存方法：</strong></p>
                        ${instructionsHtml}
                    </div>
                    <p class="file-name">📄 文件名: ${fileName}</p>
                    <div class="modal-actions">
                         <button class="action-btn primary" onclick="window.open('${url}', '_blank')">🔗 新窗口打开</button>
                         <button class="action-btn secondary" onclick="navigator.clipboard && navigator.clipboard.writeText('${url}').then(() => alert('图片链接已复制！'))">📋 复制链接</button>
                         <button class="action-btn tertiary" onclick="this.parentElement.parentElement.parentElement.querySelector('img').click()">👆 点击图片</button>
                     </div>
                     <div class="download-tips">
                         <p class="tip-title">💡 多种保存方式：</p>
                         <p class="tip-item">• 长按图片 → 保存到相册</p>
                         <p class="tip-item">• 点击"新窗口打开" → 长按保存</p>
                         <p class="tip-item">• 复制链接 → 在浏览器中打开</p>
                         <p class="tip-item">• 截屏保存（最后选择）</p>
                     </div>
                </div>
            </div>
        `;
        
        document.body.appendChild(modal);
        
        // 添加图片长按事件（移动端）
        const img = modal.querySelector('img');
        let pressTimer;
        
        img.addEventListener('touchstart', (e) => {
            pressTimer = setTimeout(() => {
                // 触发长按反馈
                img.style.transform = 'scale(0.95)';
                navigator.vibrate && navigator.vibrate(50); // 震动反馈
            }, 500);
        });
        
        img.addEventListener('touchend', () => {
            clearTimeout(pressTimer);
            img.style.transform = 'scale(1)';
        });
        
        img.addEventListener('touchmove', () => {
            clearTimeout(pressTimer);
            img.style.transform = 'scale(1)';
        });
        
        // 点击背景关闭模态框
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.remove();
            }
        });
        
        // 显示设备特定的提示信息
        const deviceEmoji = deviceType === 'ios' ? '🍎' : deviceType === 'android' ? '🤖' : '📱';
        this.showNotification(`多种保存方式已准备就绪 ${deviceEmoji}`, 'info');
        
        // 添加页面可见性检测和下载成功检测
        let downloadAttempted = false;
        
        const handleVisibilityChange = () => {
            if (!document.hidden && downloadAttempted) {
                // 用户切换回页面，可能已经保存了图片
                setTimeout(() => {
                    this.showNotification('如果图片已保存成功，可以关闭此窗口 ✅', 'success');
                }, 1000);
                document.removeEventListener('visibilitychange', handleVisibilityChange);
            }
        };
        
        // 监听用户交互，标记下载尝试
        const markDownloadAttempt = () => {
            downloadAttempted = true;
        };
        
        modal.addEventListener('click', markDownloadAttempt);
        modal.addEventListener('touchstart', markDownloadAttempt);
        
        document.addEventListener('visibilitychange', handleVisibilityChange);
        
        // 添加自动提示
        setTimeout(() => {
            if (!downloadAttempted) {
                this.showNotification('💡 提示：长按图片或点击按钮开始保存', 'warning');
            }
        }, 5000);
    }

    async downloadAll() {
        if (this.convertedImages.length === 0) return;
        
        // 如果只有一个文件，直接下载
        if (this.convertedImages.length === 1) {
            this.downloadSingle(0);
            return;
        }
        
        // 多个文件时，创建ZIP包（简化版本：逐个下载）
        this.showNotification('开始批量下载...', 'info');
        for (let i = 0; i < this.convertedImages.length; i++) {
            setTimeout(() => {
                this.downloadSingle(i);
            }, i * 500); // 间隔500ms下载，避免浏览器阻止
        }
    }
    
    // 通知系统
    showNotification(message, type = 'info', duration = 5000) {
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.innerHTML = `
            <div class="notification-content">
                <span class="notification-icon">${this.getNotificationIcon(type)}</span>
                <span class="notification-message">${message}</span>
                <button class="notification-close" onclick="this.parentElement.parentElement.remove()">&times;</button>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        // 自动移除
        setTimeout(() => {
            if (notification.parentElement) {
                notification.remove();
            }
        }, duration);
    }
    
    getNotificationIcon(type) {
        const icons = {
            success: '✓',
            error: '✗',
            warning: '⚠',
            info: 'ℹ'
        };
        return icons[type] || icons.info;
    }
    
    // 进度条系统
    createProgressBar() {
        const progressContainer = document.createElement('div');
        progressContainer.id = 'progressContainer';
        progressContainer.className = 'progress-container';
        progressContainer.innerHTML = `
            <div class="progress-info">
                <span id="progressText">准备转换...</span>
                <span id="progressPercent">0%</span>
            </div>
            <div class="progress-bar">
                <div class="progress-fill" id="progressFill"></div>
            </div>
        `;
        
        const convertBtn = document.getElementById('convertBtn');
        convertBtn.parentNode.insertBefore(progressContainer, convertBtn.nextSibling);
    }
    
    updateProgress(percent, text) {
        const progressFill = document.getElementById('progressFill');
        const progressText = document.getElementById('progressText');
        const progressPercent = document.getElementById('progressPercent');
        
        if (progressFill) progressFill.style.width = percent + '%';
        if (progressText) progressText.textContent = text;
        if (progressPercent) progressPercent.textContent = Math.round(percent) + '%';
    }
    
    removeProgressBar() {
        const progressContainer = document.getElementById('progressContainer');
        if (progressContainer) {
            progressContainer.remove();
        }
    }
    
    // 动画效果
    animateSection(sectionId) {
        const section = document.getElementById(sectionId);
        if (section) {
            section.style.opacity = '0';
            section.style.transform = 'translateY(20px)';
            
            setTimeout(() => {
                section.style.transition = 'all 0.5s ease';
                section.style.opacity = '1';
                section.style.transform = 'translateY(0)';
            }, 100);
        }
    }
}

// 初始化应用
const imageConverter = new ImageConverter();

// 防止页面默认的拖拽行为
document.addEventListener('dragover', (e) => e.preventDefault());
document.addEventListener('drop', (e) => e.preventDefault());